<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { validateLogin, login } from '../store.js'

const router = useRouter()
const isLoginMode = ref(true) // true for login, false for register

// Login form data
const loginUsername = ref('')
const loginPassword = ref('')
const loginError = ref('')

// Register form data
const registerUsername = ref('')
const registerPassword = ref('')
const registerConfirmPassword = ref('')
const registerEmail = ref('')
const registerError = ref('')
const registerSuccess = ref('')

const isLoading = ref(false)

// 登录功能
const handleLogin = async () => {
  // Reset error
  loginError.value = ''

  // Validate inputs
  if (!loginUsername.value || !loginPassword.value) {
    loginError.value = '请输入用户名和密码'
    return
  }

  isLoading.value = true

  try {
    // 验证用户名和密码
    const isValid = validateLogin(loginUsername.value, loginPassword.value)
    
    if (isValid) {
      // 登录成功，设置用户状态
      await login({
        username: loginUsername.value
      })
      
      // 登录成功后跳转到个人主页
      router.push('/profile')
    } else {
      loginError.value = '用户名或密码错误'
    }
  } catch (error) {
    loginError.value = '登录失败，请重试'
    console.error('Login error:', error)
  } finally {
    isLoading.value = false
  }
}

// 注册功能
const handleRegister = async () => {
  // Reset errors and success message
  registerError.value = ''
  registerSuccess.value = ''

  // Validate inputs
  if (!registerUsername.value || !registerPassword.value || !registerConfirmPassword.value) {
    registerError.value = '请填写所有必填字段'
    return
  }

  if (registerPassword.value !== registerConfirmPassword.value) {
    registerError.value = '两次输入的密码不一致'
    return
  }

  if (registerPassword.value.length < 6) {
    registerError.value = '密码长度至少为6位'
    return
  }

  isLoading.value = true

  try {
    // 检查用户是否已存在
    const users = JSON.parse(localStorage.getItem('users')) || []
    const existingUser = users.find(user => user.username === registerUsername.value)
    
    if (existingUser) {
      registerError.value = '用户名已被占用'
      return
    }

    // 创建新用户
    const newUser = {
      id: Math.random().toString(36).substring(2, 9),
      username: registerUsername.value,
      email: registerEmail.value,
      password: registerPassword.value, // 实际项目中应该加密存储
      avatar: `https://picsum.photos/200/200?random=${Math.floor(Math.random() * 100)}`,
      bio: '',
      following: 0,
      followers: 0,
      joinDate: new Date().toISOString()
    }

    // 保存用户到本地存储
    users.push(newUser)
    localStorage.setItem('users', JSON.stringify(users))

    // 自动登录新用户
    await login({
      username: newUser.username,
      id: newUser.id,
      avatar: newUser.avatar,
      bio: newUser.bio,
      following: newUser.following,
      followers: newUser.followers
    })

    // 注册成功后跳转到个人主页
    router.push('/profile')
  } catch (error) {
    registerError.value = '注册失败，请重试'
    console.error('Registration error:', error)
  } finally {
    isLoading.value = false
  }
}

// Toggle between login and register modes
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value
  // Clear error messages when switching modes
  loginError.value = ''
  registerError.value = ''
  registerSuccess.value = ''
}

// Switch to login mode
const switchToLogin = () => {
  isLoginMode.value = true
  registerError.value = ''
  registerSuccess.value = ''
}

// Switch to register mode
const switchToRegister = () => {
  isLoginMode.value = false
  loginError.value = ''
}

// 第三方登录
const handleWechatLogin = () => {
  console.log('微信登录')
  // 实际项目中应该调用微信登录API
}

const handleQQLogin = () => {
  console.log('QQ登录')
  // 实际项目中应该调用QQ登录API
}

const handleWeiboLogin = () => {
  console.log('微博登录')
  // 实际项目中应该调用微博登录API
}

const handleGithubLogin = () => {
  console.log('GitHub登录')
  // 实际项目中应该调用GitHub OAuth API
}
</script>

<template>
  <div class="auth-container">
    <!-- 背景图 -->
    <div class="auth-bg"></div>
    
    <!-- 登录/注册表单容器 -->
    <div class="auth-box">
      <!-- Logo -->
      <div class="logo-section">
        <div class="logo">
          <svg width="80" height="80" viewBox="0 0 40 40" fill="none">
            <rect width="40" height="40" rx="8" fill="#ff2442"/>
            <text x="20" y="26" text-anchor="middle" fill="white" font-size="18" font-weight="bold">小红书</text>
          </svg>
        </div>
        <h1>{{ isLoginMode ? '欢迎回来' : '加入小红书' }}</h1>
        <p>{{ isLoginMode ? '发现美好生活' : '分享你的生活点滴' }}</p>
      </div>
      
      <!-- 登录表单 -->
      <form v-if="isLoginMode" @submit.prevent="handleLogin">
        <div class="form-group">
          <input
            v-model="loginUsername"
            type="text"
            placeholder="请输入用户名"
            required
            :disabled="isLoading"
            class="input"
          />
        </div>
        
        <div class="form-group">
          <input
            v-model="loginPassword"
            type="password"
            placeholder="请输入密码"
            required
            :disabled="isLoading"
            class="input"
          />
        </div>
        
        <p v-if="loginError" class="error-message">{{ loginError }}</p>
        
        <button
          type="submit"
          class="auth-btn"
          :disabled="isLoading"
        >
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
      </form>
      
      <!-- 注册表单 -->
      <form v-else @submit.prevent="handleRegister">
        <div class="form-group">
          <input
            v-model="registerUsername"
            type="text"
            placeholder="请输入用户名"
            required
            :disabled="isLoading"
            class="input"
          />
        </div>
        
        <div class="form-group">
          <input
            v-model="registerEmail"
            type="email"
            placeholder="请输入邮箱（选填）"
            :disabled="isLoading"
            class="input"
          />
        </div>
        
        <div class="form-group">
          <input
            v-model="registerPassword"
            type="password"
            placeholder="请输入密码（至少6位）"
            required
            :disabled="isLoading"
            class="input"
          />
        </div>
        
        <div class="form-group">
          <input
            v-model="registerConfirmPassword"
            type="password"
            placeholder="请再次输入密码"
            required
            :disabled="isLoading"
            class="input"
          />
        </div>
        
        <p v-if="registerError" class="error-message">{{ registerError }}</p>
        
        <button
          type="submit"
          class="auth-btn"
          :disabled="isLoading"
        >
          {{ isLoading ? '注册中...' : '立即注册' }}
        </button>
      </form>
      
      <!-- 切换登录/注册 -->
      <div class="auth-toggle">
        {{ isLoginMode ? '还没有账号？' : '已有账号？' }}
        <button type="button" @click="toggleMode" class="toggle-btn">
          {{ isLoginMode ? '立即注册' : '立即登录' }}
        </button>
      </div>
      
      <!-- 第三方登录 -->
      <div class="divider">
        <span></span>
        <span>其他方式登录</span>
        <span></span>
      </div>
      
      <div class="social-login">
        <button class="social-btn wechat" @click="handleWechatLogin" :disabled="isLoading">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/>
          </svg>
        </button>
        
        <button class="social-btn qq" @click="handleQQLogin" :disabled="isLoading">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 16l-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9l-8 8z"/>
          </svg>
        </button>
        
        <button class="social-btn weibo" @click="handleWeiboLogin" :disabled="isLoading">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.42 13.41c-.27.26-.67.29-.97.07-.81-.66-1.9-1.06-3.45-1.06h-1v-6h1c2.5 0 4.65 1.44 5.37 3.51.15.41.04.87-.23 1.15l-.01.01z"/>
            <path d="M8 8h2v6H8z"/>
            <path d="M10 16h2v2h-2z"/>
          </svg>
        </button>
        
        <button class="social-btn github" @click="handleGithubLogin" :disabled="isLoading">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/>
          </svg>
        </button>
      </div>
      
      <!-- 用户协议 -->
      <div class="agreement">
        {{ isLoginMode ? '登录' : '注册' }}即表示您同意小红书的
        <a href="#" class="link">用户协议</a>
        和
        <a href="#" class="link">隐私政策</a>
      </div>
    </div>
  </div>
</template>

<style scoped>
.auth-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  overflow: hidden;
}

.auth-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('https://picsum.photos/1920/1080?random=50');
  background-size: cover;
  background-position: center;
  filter: brightness(0.8);
  z-index: -1;
}

.auth-box {
  width: 100%;
  max-width: 420px;
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  animation: fadeIn 0.6s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.logo-section {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  margin-bottom: 20px;
}

.logo-section h1 {
  font-size: 32px;
  font-weight: 700;
  color: #333;
  margin-bottom: 8px;
}

.logo-section p {
  font-size: 16px;
  color: #666;
}

.form-group {
  margin-bottom: 24px;
}

.input {
  width: 100%;
  padding: 14px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  font-size: 16px;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.7);
}

.input:focus {
  outline: none;
  border-color: #ff2442;
  box-shadow: 0 0 0 3px rgba(255, 36, 66, 0.1);
}

.error-message {
  color: #ff2442;
  font-size: 14px;
  margin-bottom: 20px;
  text-align: center;
}

.auth-btn {
  width: 100%;
  padding: 14px;
  background-color: #ff2442;
  color: white;
  border: none;
  border-radius: 50px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.auth-btn:hover:not(:disabled) {
  background-color: #e01b37;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 36, 66, 0.3);
}

.auth-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.auth-toggle {
  margin-top: 24px;
  text-align: center;
  color: #666;
  font-size: 14px;
}

.toggle-btn {
  color: #ff2442;
  background: none;
  border: none;
  font-size: 14px;
  cursor: pointer;
  font-weight: 600;
  padding: 0;
  margin-left: 4px;
}

.divider {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 32px 0;
}

.divider span:not(:nth-child(2)) {
  flex: 1;
  height: 1px;
  background-color: #e0e0e0;
}

.divider span:nth-child(2) {
  padding: 0 16px;
  color: #999;
  font-size: 14px;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 32px;
  margin-bottom: 24px;
}

.social-btn {
  width: 52px;
  height: 52px;
  border-radius: 50%;
  border: 1px solid #e0e0e0;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.social-btn:hover:not(:disabled) {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.social-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.social-btn.wechat {
  color: #07C160;
}

.social-btn.qq {
  color: #12B7F5;
}

.social-btn.weibo {
  color: #E6162D;
}

.agreement {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin-top: 16px;
}

.agreement .link {
  color: #ff2442;
  text-decoration: none;
}

@media (max-width: 768px) {
  .auth-box {
    margin: 20px;
    padding: 32px 24px;
  }
  
  .social-login {
    gap: 24px;
  }
  
  .social-btn {
    width: 48px;
    height: 48px;
  }
}
</style>